import React, {memo, useCallback, useEffect, useState} from 'react';
import {AddArticleWrapper} from "./style";

import {Row, Col, Input, Select, Button} from 'antd';
import setMessage from "@/utils/setMessage";
import MdEditor from "react-markdown-editor-lite";
import MarkdownIt from "markdown-it";
import hljs from "highlight.js";
import emoji from "markdown-it-emoji";
import subscript from "markdown-it-sub";
import superscript from "markdown-it-sup";
import footnote from "markdown-it-footnote";
import deflist from "markdown-it-deflist";
import abbreviation from "markdown-it-abbr";
import insert from "markdown-it-ins";
import mark from "markdown-it-mark";
import tasklists from "markdown-it-task-lists";
import 'react-markdown-editor-lite/lib/index.css';
import 'highlight.js/styles/atom-one-dark.css';

import {withRouter} from "react-router";
import {
  getArticleDetail,
  createArticle,
  updateArticle
} from "@/network/article.request";
import {getArticleClassify} from "@/network/archives.request";
import {getClassifyId} from "@/utils/common";
import {uploadArticlePic} from "@/network/file.request";

const {Option} = Select;

function AddArticle(props) {

  const {userId} = props;
  const [articleId, setArticleId] = useState("0");
  const [articleTitle, setArticleTitle] = useState("")   // 文章标题
  const [articleContent, setArticleContent] = useState("")  // markdown的编辑内容
  // const [markdownContent, setMarkdownContent] = useState("预览内容") // markdown的预览内容
  const [typeInfo, setTypeInfo] = useState([]) // 文章类别信息
  const [selectedType, setSelectType] = useState("") // 选择的文章类别

  useEffect(() => {
    setArticleId(props.match.params["a_id"])
  }, [props.match.params])

  useEffect(() => {
    if (String(articleId) === "0") { // 创建
      setArticleTitle("");
      setArticleContent("");
      setSelectType("");
    } else {
      getArticleDetail(articleId).then(res => { // 修改
        setArticleTitle(res.title);
        setArticleContent(res.content);
        setSelectType(res.classifyName);
      }).catch(console.log)
    }
  }, [articleId, props.match.params])

  useEffect(() => {
    getArticleClassify(userId).then(res => {
      setTypeInfo(res);
      setSelectType(res[0].classify)
    }).catch(console.log)
  }, [userId])

  // let mdEditor = null
  const mdParser = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    highlight: function (str, lang) {
      if (lang && hljs.getLanguage(lang)) {
        try {
          return hljs.highlight(lang, str).value
        } catch (err) {
          console.log(err)
        }
      }
      return ''
    }
  })
    .use(emoji)
    .use(subscript)
    .use(superscript)
    .use(footnote)
    .use(deflist)
    .use(abbreviation)
    .use(insert)
    .use(mark)
    .use(tasklists, {enabled: true})

  const handleEditorChange = useCallback(({html, md}) => {
    setArticleContent(md);
    // setMarkdownContent(html);
  }, [])

  const handleImageUpload = useCallback((file, callback) => {
    const {name, size} = file;
    let type = name.split(".").pop();
    if (["jpg", "jpeg", "png", "webp"].includes(type) && size < 5 * 1024 * 1024) {
      const formData = new FormData()
      formData.append('article_pic', file);
      uploadArticlePic(formData).then(res => {
        callback(res.url);
      }).catch(console.log)
    } else {
      setMessage("选择的文件不符合要求", "info");
    }
  }, []);

  const renderHTML = (text) => {
    // 模拟异步渲染Markdown
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(mdParser.render(text))
      }, 300)
    }).catch(console.log)
  }

  // 发表文章
  const handlePublicArticle = useCallback(() => {
    const content = document.querySelector(".editor-container .sec-md textarea").value;
    const classifyId = getClassifyId(typeInfo, selectedType)
    if (String(articleId) === "0") {
      // 新建
      if (articleTitle.length > 0 && content.length > 0 && classifyId) {
        createArticle(articleTitle, classifyId, content, content.length).then(res => {
          if (res.insertId) {
            setMessage("发布成功", "success");
          } else {
            setMessage("发布失败", "error");
          }
        }).catch(console.log)
      } else {
        setMessage("文章要素不完整, 发布失败", "info");
      }
    } else {
      // 修改
      if (articleTitle.length > 0 && content.length > 0 && classifyId) {
        updateArticle(articleTitle, classifyId, content, content.length, articleId).then(res => {
          if (res.affectedRows) {
            setMessage("修改成功", "success");
          } else {
            setMessage("发布失败", "error");
          }
        }).catch(console.log)
      } else {
        setMessage("文章要素不完整, 修改失败", "info");
      }
    }
  }, [articleId, articleTitle, typeInfo, selectedType])

  return (
    <AddArticleWrapper>
      <Row gutter={5}>
        <Col span={19}>
          <Row gutter={10}>
            <Col span={20}>
              <Input
                placeholder="文章标题"
                size="large"
                value={articleTitle}
                onChange={e => setArticleTitle(e.target.value)}
              />
            </Col>
            <Col span={4}>
              <Select
                defaultValue={(typeInfo && typeInfo.length > 0) && typeInfo[0].classify}
                value={selectedType || (typeInfo && typeInfo.length > 0 && typeInfo[0].classify) || "暂无归档"}
                size="large"
                onChange={value => setSelectType(value)}
              >
                {
                  typeInfo && typeInfo.length > 0 && typeInfo.map((item) => {
                    return <Option key={item.id} value={item.classify}>{item.classify}</Option>
                  })
                }
              </Select>
            </Col>
          </Row>
        </Col>
        <Col span={5}>
          <Row>
            <Col span={24}>
              <Button
                size="large"
                className="mr-4"
                onClick={e => setMessage("暂不支持", "warn")}>
                暂存文章
              </Button>
              <Button
                type="primary"
                size="large"
                onClick={handlePublicArticle}>
                发布文章
              </Button>
            </Col>
          </Row>
        </Col>
      </Row>
      <Row gutter={10} className="pt-5">
        <Col span={24}>
          <section className="home-a-content" style={{height: "78vh", overflow: "scroll"}}>
            <MdEditor
              // ref={node => mdEditor = node}
              value={articleContent}
              placeholder="请输入文字"
              style={{height: '75vh'}}
              renderHTML={renderHTML}
              config={{
                view: {
                  menu: true,
                  md: true,
                  html: true
                }
              }}
              onChange={handleEditorChange}
              onImageUpload={handleImageUpload}
            />
          </section>
        </Col>
      </Row>
    </AddArticleWrapper>
  )
}

export default memo(withRouter(AddArticle))
